package com.nl.lib_core.mvp

import android.content.Context
import androidx.lifecycle.LifecycleOwner

/** 作者: wangfei 创建时间: 2021/9/1 包名: com.nl.lib_core.mvp 类名: BasePresenter */
abstract class BasePresenter<BM : BaseModel, V>(protected var context: Context) {

  protected var mView: V? = null

  protected var mBaseModel: BM? = null

  protected var mLifecycleOwner: LifecycleOwner? = null

  fun attach(view: V) {
    attachView(view)
    attachModel()
  }

  open fun detach() {
    detachView()
    detachModel()
  }

  private fun attachView(view: V) {
    mView = view
  }

  private fun detachView() {
    mView = null
  }

  private fun attachModel() {
    mBaseModel = initModel()
  }

  private fun detachModel() {
    mBaseModel?.destroy()
    mBaseModel = null
  }

  abstract fun initModel(): BM

  fun injectLifecycleOwner(lifecycleOwner: LifecycleOwner) {
    mLifecycleOwner = lifecycleOwner
    mBaseModel?.injectLifecycleOwner(mLifecycleOwner!!)
  }

  companion object {
    val TAG = BasePresenter::class.java.simpleName
  }
}
